package com.acertificate.domain;

import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.spi.CharsetProvider;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.util.EntityUtils;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.ParagraphTag;
import org.htmlparser.util.NodeList;

public class Test {

	public static void main(String[] args) throws Exception {
		HttpPost httppost = new HttpPost("http://dafau.sinaapp.com/share/mood");
		HttpClient httpclient = new DefaultHttpClient();
		
		
		String url = "http://gexing.51gxqm.com/qianming/index.html";
		String content = null;
		URLConnection urlConnection = new URL(url).openConnection();
		String content1 = IOUtils.toString(urlConnection.getInputStream());
		Parser contentParser = new Parser();
		contentParser.setInputHTML(content1);

		AndFilter andFilter = new AndFilter(new NodeClassFilter(Div.class), new HasAttributeFilter("class", "feedCon"));
		NodeList xx = contentParser.extractAllNodesThatMatch(andFilter);
		for (int i = 0; i < xx.size(); i++) {
			Node node = xx.elementAt(i);
			content = node.toPlainTextString();
			String[] lines = content.split("\n");
			String first = lines[1];
			String name2Type = first.split("&nbsp;")[0];

			MultipartEntity reqEntity = new MultipartEntity();
			
			StringBody field3 = new StringBody(name2Type.substring(0, name2Type.indexOf("[")), Charset.forName( "UTF-8" ));
			StringBody field2 = new StringBody(name2Type.substring(name2Type.indexOf("[") + 1, name2Type.indexOf("]")), Charset.forName( "UTF-8" ));
			StringBody field1 = new StringBody(lines[2], Charset.forName( "UTF-8" ));
			
			reqEntity.addPart("field1", field1);
			reqEntity.addPart("field2", field2);
			reqEntity.addPart("field3", field3);
			
			httppost.setEntity(reqEntity);
			
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			if (resEntity != null) {
				System.out.println(IOUtils.toString(resEntity.getContent()));
			}
			EntityUtils.consume(resEntity);

		}
	}

}
